package com.zxc.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zxc.common.constant.ProductConstant;
import com.zxc.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.zxc.gulimall.product.dao.AttrGroupDao;
import com.zxc.gulimall.product.dao.CategoryDao;
import com.zxc.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.zxc.gulimall.product.entity.AttrGroupEntity;
import com.zxc.gulimall.product.entity.CategoryEntity;
import com.zxc.gulimall.product.service.AttrAttrgroupRelationService;
import com.zxc.gulimall.product.service.AttrGroupService;
import com.zxc.gulimall.product.service.CategoryService;
import com.zxc.gulimall.product.vo.AttrGroupRelationVo;
import com.zxc.gulimall.product.vo.AttrRespVo;
import com.zxc.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.common.utils.PageUtils;
import com.zxc.common.utils.Query;

import com.zxc.gulimall.product.dao.AttrDao;
import com.zxc.gulimall.product.entity.AttrEntity;
import com.zxc.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        System.out.println("attrIds====="+attrIds);
        //返回值为attrIds ， searchType = 1
        List<Long> attrIdList = baseMapper.selectSearchAttrs(attrIds);
        return attrIdList;
    }

    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        //1、我们首先根据attrgroupId查找出对应的attr_group表里面的数据
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //2、根据我们查找出的attrGroupEntity查找出表里面的catelog_id和这个实体类一样的表数据。
        Long catelogId = attrGroupEntity.getCatelogId();
        QueryWrapper<AttrGroupEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        //1）、首先我们的catelog_id得一样,包括自己已经关联的属性
        attrEntityQueryWrapper.eq("catelog_id",catelogId);
        List<AttrGroupEntity> attrEntityList = attrGroupDao.selectList(attrEntityQueryWrapper);
        //2）、把这个查找出来的集合的主键id集合
        List<Long> attrGroupIdList = attrEntityList.stream().map(attrGroup -> {
            return attrGroup.getAttrGroupId();
        }).collect(Collectors.toList());
        //3、根据这个集合我们在关系表中找出所有和这些Id关联了的属性
        //1）、首先我们得保证我们的attrGroupIdList里面有数据我们才能在表里面查找出来数据
        List<AttrAttrgroupRelationEntity> entities = new ArrayList<>();
        if (attrGroupIdList != null && attrEntityList.size() > 0){
            QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
            attrAttrgroupRelationEntityQueryWrapper.in("attr_group_id", attrGroupIdList);
            entities = attrAttrgroupRelationDao.selectList(attrAttrgroupRelationEntityQueryWrapper);
        }
        //2)、根据查找出来的数据提取出对应的attr_id
        List<Long> attrIdList = entities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //4、在属性表里面查找出没有关联的属性，并且是基本属性，不能是销售属性，还得catelog_id得是一致的
        QueryWrapper<AttrEntity> entityQueryWrapper = new QueryWrapper<>();
        entityQueryWrapper.notIn("attr_id",attrIdList).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).eq("catelog_id",catelogId);
        //5、查找出来数据之后我们需要对这个数据进行分页处理
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            //如果不为空，我们需要进行模糊查询
            entityQueryWrapper.eq("attr_id",key).or().eq("attr_name",key);
        }

        if (attrIdList != null && attrIdList.size() > 0){
            //6、需要进行分页显示
            IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),entityQueryWrapper);
            return new PageUtils(page);
        }
        return null;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",1L).eq("attr_group_id",2L));
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item,attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(collect);
    }



    //根据分组关联Id找到
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));
        List<Long> collect = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(collect == null || collect.size() == 0){
            //说明没有关联的数据
            return null;
        }
        List<AttrEntity> attrEntities = this.listByIds(collect);
        return attrEntities;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        //1、修改分组关联
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());

            Integer attr_id = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (attr_id > 0){
                attrAttrgroupRelationDao.
                        update(attrAttrgroupRelationEntity,
                                new UpdateWrapper<AttrAttrgroupRelationEntity>()
                                        .eq("attr_id",attr.getAttrId()));

            }else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }


    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();

        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //根据attrId查询出关系表里面的attrGroupId
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrAttrgroupRelationEntity != null) {
                attrRespVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }


        //设置分类信息
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        Long[] catelogPath = categoryService.findCategoryPath(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(catelogPath);
        if (categoryEntity != null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }

        return attrRespVo;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId,String type) {
        QueryWrapper<AttrEntity> queryWrapper= new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        Object key = params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
               wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),queryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        PageUtils pageUtils = new PageUtils(page);
        List<AttrRespVo> attrRespVoList = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity,attrRespVo);

            //1、根据attrEntity里的id在对应的关系表里面查找对应的数据
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("attr_id",attrEntity.getAttrId());
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(queryWrapper1);
            if ("base".equalsIgnoreCase(type)){
                if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null){
                    //2、通过查询到的实体类的attr_group_id查找对应的表里面的数据，并设置组名
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            //3、通过attrEntity类对应的catelog_id查询对应的category表里面的name
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespVoList);

        return pageUtils;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);//需要注意的是，两个类的属性名需要一致才能赋值完成
        this.save(attrEntity);

        //保存关联关系表数据attr and attr_group 表数据
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }

    }
}